package com.weilive.api.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinanetcenter.api.domain.HttpClientResult;
import com.chinanetcenter.api.domain.PutPolicy;
import com.chinanetcenter.api.util.Config;
import com.chinanetcenter.api.wsbox.FileDownCommand;
import com.chinanetcenter.api.wsbox.FileManageCommand;
import com.chinanetcenter.api.wsbox.FileUploadCommand;
import com.weilive.api.ServerConfig;
import com.weilive.core.utils.FileUtils;
import com.weilive.core.utils.HttpUtils;
import com.weilive.core.utils.MD5Utils;

/**
 * 网宿操作接口
 * 
 * @author houzhiwei
 *
 */
public final class WcsUtil {
	private static final Logger logger = LoggerFactory.getLogger(WcsUtil.class);
	// 空间名称
	private static final String BUCKEY_NAME = ServerConfig.getWcsBuckeyName();// 空间名:文件名
	// 秒级禁播配置
	private static final String URL = ServerConfig.getWcsReqURL();
	private static final String USER_NAME = ServerConfig.getWcsReqUserName();
	private static final String USER_PASSWORD = ServerConfig.getWcsReqUserPass();
	private static final String UPSTRAM_URL = ServerConfig.getWcsReqUpstreamURL();

	private static final String ACCESS_KEY = "2646a95ed0e143140b8548508e08573ee8ef9b6d";// 访问秘钥
	private static final String SECRET_KEY = "4d490734680f3bb4f87bfa30b6dc5768b2db1419";// 安全秘钥
	private static final String FILE_DIR = FileUtils.getResourcePath(".") + "/download/";

	static {
		Config.init(ACCESS_KEY, SECRET_KEY);
	}

	/**
	 * 删除文件
	 * 
	 * @param fileName
	 *            完整文件名
	 * 
	 * @return
	 */
	public static final boolean deleteVdo(String fileName) {
		if (StringUtils.isBlank(fileName)) {
			return true;
		}

		HttpClientResult httpClientResult = FileManageCommand.delete(BUCKEY_NAME, fileName);

		return httpClientResult.getStatus() == 200 ? true : false;
	}

	/**
	 * 按文件名前缀删除
	 * 
	 * @param filePrefix
	 *            文件前缀
	 * @return
	 */
	public static final boolean deleteVdoPrefix(String filePrefix) {

		if (StringUtils.isBlank(filePrefix)) {
			return true;
		}

		String m3u8FileName = filePrefix + ".m3u8";// 寻找切片文件 前缀

		List<String> deleteTsFile = getDeleteTsFile(m3u8FileName);

		HttpClientResult httpClientResult = FileManageCommand.deletePrefix(BUCKEY_NAME, filePrefix + ".m3u8");
		httpClientResult = FileManageCommand.deletePrefix(BUCKEY_NAME, filePrefix + ".mp4");
		httpClientResult = FileManageCommand.deletePrefix(BUCKEY_NAME, filePrefix + ".jpg");

		if (httpClientResult.getStatus() == 200 && deleteTsFile != null) {
			for (String file : deleteTsFile) {
				httpClientResult = FileManageCommand.delete(BUCKEY_NAME, file);
			}
		}

		return httpClientResult.getStatus() == 200 ? true : false;
	}

	/**
	 * 获取ts文件的删除前缀
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static final List<String> getDeleteTsFile(String fileName) {
		// 判断文件是否存在
		HttpClientResult isExist = FileManageCommand.stat(BUCKEY_NAME, fileName);
		if (isExist.getStatus() != 200) {
			logger.info("m3u8文件不存在,无需删除ts文件!fileName=" + fileName);
			return null;
		}
		// 目标文件名
		String destFile = FILE_DIR + fileName;

		logger.info("下载目录:" + destFile);

		File file = null;
		try {
			file = new File(destFile);
			// 创建目标文件
			FileUtils.createFile(file);

			HttpClientResult httpClientResult = FileDownCommand.download(BUCKEY_NAME, fileName, destFile);

			if (httpClientResult.getStatus() != 200) {
				logger.info("下载文件失败!fileName=" + fileName);
				return null;
			}
			return readTsFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (file != null && file.exists()) {
				file.delete();
			}
		}
		return null;
	}

	/**
	 * 获取网速的ts文件前缀
	 * 
	 * @param file
	 * @return
	 */
	private static List<String> readTsFile(File file) {
		BufferedReader reader = null;
		try {

			reader = new BufferedReader(new FileReader(file));
			List<String> list = new ArrayList<String>();
			String line = "";
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				if (line.length() == 0 || line.startsWith("#")) {
					continue;
				}
				if (line.endsWith(".ts")) {
					list.add(line);
				}
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	/**
	 * 文件上传
	 * 
	 * @param filePath
	 * @param fileName
	 * @return
	 */
	public static final String uploadFile(String filePath, String fileName) {

		String returnBody = "url=$(url)"; // 自定义返回信息
		HttpClientResult httpClientResult = FileUploadCommand.uploadFileAndReturn(BUCKEY_NAME, fileName, filePath,
				returnBody);

		if (httpClientResult.getStatus() == 200) {
			return getURL(httpClientResult.getResponse());
		}
		return "";
	}

	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param fileName
	 * @return
	 */
	public static final String uploadFile(byte[] file, String fileName) {

		String returnBody = "url=$(url)"; // 自定义返回信息
		ByteArrayInputStream in = new ByteArrayInputStream(file);

		PutPolicy policy = new PutPolicy();
		policy.setReturnBody(returnBody);
		policy.setOverwrite(1);

		HttpClientResult httpClientResult = FileUploadCommand.upload(BUCKEY_NAME, fileName, "", in, policy);
		if (httpClientResult.getStatus() == 200) {
			return getURL(httpClientResult.getResponse());
		}
		return "";
	}

	private static final String getURL(String result) {

		String[] str = result.split("&");
		for (String s : str) {
			if (s.contains("url")) {
				return s.split("=")[1];
			}
		}
		return "";
	}

	public static final String getFileKey(String url) {
		if (StringUtils.isBlank(url)) {
			return "";
		}
		try {
			String filePrefix = url.substring(url.lastIndexOf("/") + 1, url.length());

			filePrefix = filePrefix.substring(0, filePrefix.lastIndexOf("."));
			return filePrefix;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 禁止或者恢复用户的推流权限
	 * 
	 * @param userId
	 *            1043481
	 * @param status
	 *            0:关闭,1:恢复
	 * @throws Exception
	 */
	public static boolean setWcsPush(long userId, int status) throws Exception {

		final String cmd = "channel_manager";// 写死的
		final String type = "play";// play，publish 表示重启拉流频道还是推流频道。

		// rtmp://upstream.weilive.cc/live/1043481
		final String channel = UPSTRAM_URL + userId;// 推流地址
		String action = "forbid";// 方式,禁止和恢复
		if (status == 1) {
			action = "resume";// 恢复
		}

		String sign = MD5Utils.encryptToHex(USER_NAME + USER_PASSWORD + channel);

		String goURL = String.format("%scmd=%s&type=%s&username=%s&password=%s&action=%s&channel=%s", URL, cmd, type,
				USER_NAME, sign, action, channel);

		
		System.out.println(goURL);
		String result = HttpUtils.HttpGetGo(goURL);

		return result.equals("success append purge tasks");
	}

	public static void main(String[] args) throws Exception {

		// deleteVdoPrefix("XGbyHEXjhnSLuzMBI8Imylive.501.4c8ce6cda2c140438e85412b77b71cef");

		System.out.println(setWcsPush(1043408, 0));

		// for (int i = 1; i <= 9; i++) {
		// System.out.println(uploadFile("D://05test.mp4", "test00" + i +
		// ".mp4"));
		// }
	}
}
